package com.gjy.rabbitmq.resolve;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;

import java.util.concurrent.TimeUnit;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-10-13 14:43:23
 */
public class RedisUtil {

    private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);

    /**
     * Jedis连接池
     */
    private final JedisPool jedisPool;

    /**
     * 构造Redis工具类
     *
     * @param jedisPool Jedis连接池
     */
    public RedisUtil(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
        logger.info("Redis工具类初始化完成");
    }

    /**
     * 设置键值对，如果键不存在（原子操作）
     *
     * @param key     键
     * @param value   值
     * @param timeout 过期时间
     * @param unit    时间单位
     * @return 设置是否成功
     */
    public boolean setIfAbsent(String key, String value, long timeout, TimeUnit unit) {
        try (Jedis jedis = jedisPool.getResource()) {
            SetParams params = new SetParams();
            params.nx().ex(unit.toSeconds(timeout));
            String result = jedis.set(key, value, params);
            boolean success = "OK".equals(result);
            if (success) {
                logger.debug("Redis设置键成功: key={}", key);
            } else {
                logger.debug("Redis键已存在: key={}", key);
            }
            return success;
        } catch (Exception e) {
            logger.error("Redis设置键失败: key={}", key, e);
            return false;
        }
    }

    /**
     * 删除键
     *
     * @param key 键
     */
    public void delete(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            Long result = jedis.del(key);
            logger.debug("Redis删除键: key={}, result={}", key, result);
        } catch (Exception e) {
            logger.error("Redis删除键失败: key={}", key, e);
        }
    }

    /**
     * 检查键是否存在
     *
     * @param key 键
     * @return 键是否存在
     */
    public boolean exists(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            Boolean result = jedis.exists(key);
            logger.debug("Redis检查键存在: key={}, result={}", key, result);
            return result;
        } catch (Exception e) {
            logger.error("Redis检查键存在失败: key={}", key, e);
            return false;
        }
    }

}
